<template>
  <div class="image-upload">
    <!-- 图片列表 -->
    <div class="image-list">
      <div
        v-for="(image, index) in imageList"
        :key="index"
        class="image-item"
        :class="{ 'is-main': image.imageType === 1 }"
      >
        <div class="image-wrapper">
          <el-image
            :src="image.imageUrl"
            :preview-src-list="previewList"
            :initial-index="index"
            fit="cover"
            class="image"
          />
          <div class="image-overlay">
            <div class="image-actions">
              <el-button
                type="primary"
                size="small"
                :icon="View"
                circle
                @click="handlePreview(image, index)"
              />
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                circle
                @click="handleRemove(index)"
              />
            </div>
          </div>
        </div>
        <div class="image-info">
          <div class="image-type">
            <el-tag
              :type="image.imageType === 1 ? 'success' : 'info'"
              size="small"
            >
              {{ image.imageType === 1 ? '主图' : '详情图' }}
            </el-tag>
          </div>
          <div class="image-sort">
            <el-input-number
              v-model="image.sortOrder"
              :min="0"
              :max="999"
              size="small"
              controls-position="right"
              @change="handleSortChange"
            />
          </div>
        </div>
        <div class="image-actions-bottom">
          <el-button
            v-if="image.imageType !== 1"
            type="success"
            size="small"
            @click="handleSetMain(index)"
          >
            设为主图
          </el-button>
        </div>
      </div>
      
      <!-- 上传按钮 -->
      <div
        v-if="imageList.length < maxCount"
        class="upload-item"
        @click="handleUpload"
      >
        <el-icon class="upload-icon"><Plus /></el-icon>
        <div class="upload-text">上传图片</div>
        <div class="upload-tip">最多{{ maxCount }}张，单张不超过{{ maxSize }}MB</div>
      </div>
    </div>
    
    <!-- 上传提示 -->
    <div v-if="imageList.length === 0" class="upload-empty">
      <el-icon class="empty-icon"><Picture /></el-icon>
      <div class="empty-text">暂无图片，点击上方按钮上传</div>
    </div>
    
    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInputRef"
      type="file"
      :accept="accept"
      multiple
      style="display: none"
      @change="handleFileChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, View, Picture } from '@element-plus/icons-vue'
import type { ProductImageRequest } from '@/api/product'

// 定义属性
const props = defineProps<{
  modelValue: ProductImageRequest[]
  maxCount?: number
  maxSize?: number // MB
  accept?: string
}>()

// 定义事件
const emit = defineEmits<{
  'update:modelValue': [value: ProductImageRequest[]]
}>()

// 默认值
const maxCount = props.maxCount || 10
const maxSize = props.maxSize || 5
const accept = props.accept || 'image/*'

// 响应式数据
const fileInputRef = ref<HTMLInputElement>()
const imageList = ref<ProductImageRequest[]>([])

// 计算属性
const previewList = computed(() => imageList.value.map(img => img.imageUrl))

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newValue) => {
    imageList.value = newValue ? [...newValue] : []
  },
  { immediate: true, deep: true }
)

// 监听imageList变化，同步到父组件
watch(
  imageList,
  (newValue) => {
    emit('update:modelValue', [...newValue])
  },
  { deep: true }
)

// 处理文件选择
const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files
  
  if (!files || files.length === 0) return
  
  // 检查数量限制
  if (imageList.value.length + files.length > maxCount) {
    ElMessage.warning(`最多只能上传${maxCount}张图片`)
    return
  }
  
  // 处理每个文件
  Array.from(files).forEach(file => {
    handleFile(file)
  })
  
  // 清空input
  target.value = ''
}

// 处理单个文件
const handleFile = (file: File) => {
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return
  }
  
  // 检查文件大小
  if (file.size > maxSize * 1024 * 1024) {
    ElMessage.error(`图片大小不能超过${maxSize}MB`)
    return
  }
  
  // 创建FileReader
  const reader = new FileReader()
  reader.onload = (e) => {
    const imageUrl = e.target?.result as string
    
    // 创建图片对象
    const newImage: ProductImageRequest = {
      imageUrl,
      imageType: imageList.value.length === 0 ? 1 : 2, // 第一张设为主图
      sortOrder: imageList.value.length
    }
    
    imageList.value.push(newImage)
  }
  
  reader.readAsDataURL(file)
}

// 开始上传
const handleUpload = () => {
  fileInputRef.value?.click()
}

// 预览图片
const handlePreview = (image: ProductImageRequest, index: number) => {
  // 这里可以添加自定义预览逻辑
  console.log('预览图片:', image, index)
}

// 删除图片
const handleRemove = async (index: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const removedImage = imageList.value[index]
    imageList.value.splice(index, 1)
    
    // 如果删除的是主图，自动设置第一张为主图
    if (removedImage.imageType === 1 && imageList.value.length > 0) {
      imageList.value[0].imageType = 1
    }
    
    // 重新排序
    imageList.value.forEach((img, idx) => {
      img.sortOrder = idx
    })
    
    ElMessage.success('删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

// 设为主图
const handleSetMain = (index: number) => {
  // 取消其他主图
  imageList.value.forEach(img => {
    img.imageType = 2
  })
  
  // 设置新的主图
  imageList.value[index].imageType = 1
  
  ElMessage.success('设置主图成功')
}

// 排序变化
const handleSortChange = () => {
  // 按排序字段重新排序
  imageList.value.sort((a, b) => a.sortOrder - b.sortOrder)
  
  // 重新设置排序值
  imageList.value.forEach((img, index) => {
    img.sortOrder = index
  })
}

// 拖拽排序（可选功能）
const handleDragStart = (index: number) => {
  // 实现拖拽排序逻辑
  console.log('开始拖拽:', index)
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
}

const handleDrop = (event: DragEvent, targetIndex: number) => {
  event.preventDefault()
  // 实现拖拽排序逻辑
  console.log('拖拽到:', targetIndex)
}
</script>

<style lang="scss" scoped>
.image-upload {
  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
  }
  
  .image-item {
    position: relative;
    width: 120px;
    border: 2px solid #dcdfe6;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s;
    
    &.is-main {
      border-color: #67c23a;
      box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
    }
    
    &:hover {
      border-color: #409eff;
      
      .image-overlay {
        opacity: 1;
      }
    }
    
    .image-wrapper {
      position: relative;
      width: 100%;
      height: 120px;
      
      .image {
        width: 100%;
        height: 100%;
      }
      
      .image-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s;
        
        .image-actions {
          display: flex;
          gap: 8px;
        }
      }
    }
    
    .image-info {
      padding: 8px;
      background: #f8f9fa;
      
      .image-type {
        margin-bottom: 4px;
        text-align: center;
      }
      
      .image-sort {
        text-align: center;
      }
    }
    
    .image-actions-bottom {
      padding: 8px;
      text-align: center;
      background: #f8f9fa;
      border-top: 1px solid #ebeef5;
    }
  }
  
  .upload-item {
    width: 120px;
    height: 120px;
    border: 2px dashed #dcdfe6;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      border-color: #409eff;
      color: #409eff;
    }
    
    .upload-icon {
      font-size: 24px;
      margin-bottom: 8px;
    }
    
    .upload-text {
      font-size: 14px;
      margin-bottom: 4px;
    }
    
    .upload-tip {
      font-size: 12px;
      color: #909399;
      text-align: center;
      line-height: 1.2;
    }
  }
  
  .upload-empty {
    text-align: center;
    padding: 40px;
    color: #909399;
    
    .empty-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }
    
    .empty-text {
      font-size: 14px;
    }
  }
}

:deep(.el-image) {
  border-radius: 4px;
}

:deep(.el-input-number) {
  width: 80px;
}
</style>

